<?php
namespace app\admin\controller;
header("content-type:text/html;charset=utf-8");
use app\admin\controller\Base;
use app\admin\model\Admin;
use app\admin\model\Apply;
use app\admin\model\Applytype;
use app\admin\model\Classtype;
use app\admin\model\Course;
use app\admin\model\Coursetype;
use app\admin\model\Dustbin;
use app\admin\model\Examtype;
use app\admin\model\Myclass;
use app\admin\model\Nation;
use app\admin\model\Naturetype;
use app\admin\model\Teacher;
use app\admin\model\User;
use app\admin\model\Usertype;
use think\App;
use think\facade\Db;
use think\Request;
use think\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class  Search extends Base
{
  //修改视图
  public function update(Request $request)
  {
    $user = $this->user_info();
    $id = $request->get("id");
    $apply = Apply::where(array("id" => $id))->find();
    $data = array(
      "setting" => $this->getAllSetting(),
      "status" => Applytype::select(),
      "data" => $apply,
      "user" => User::where(array("id" => $apply['userid']))->find(),
      "teacher"=>Teacher::all()
    );
    return view("update", $data);
  }
  public function toUpdate(Request $request)
  {
    $user = $this->user_info();
    $data = $request->post();
    $naturetext = Naturetype::where(array("id" => $data['natrueid']))->find();
    $data['natrue'] = $naturetext['type_name'];
    $coursetext = Course::where(array("id" => $data['courseid']))->find();
    $data['course'] = $coursetext['name'];
    $data['update_time'] = time();
    if (Apply::update($data)) {
      $this->success("修改成功","Search/search");
    } else {
      $this->error("修改失败");
    }

  }
  public function deletes(Request $request)
  {
      $user = $this->user_info();
      $apply = Apply::get($request->post('id'));
      $user = User::get($apply['userid']);
      $del_comment = $request->post("del_comment");
      $arr = array(
          "major"=>$apply['major'],
          "bktype"=>$apply['bktype'],
          "apply_create_time"=>strtotime($apply['create_time']),
          "apply_update_time"=>strtotime($apply['update_time']),
          "reason"=>$apply['reason'],
          "comment"=>$apply['comment'],
          "status"=>$apply['status'],
          "paytype"=>$apply['paytype'],
          "payid"=>$apply['payid'],
          "type"=>$apply['type'],
          "pay_time"=>$apply['pay_time'],
          "major2"=>$apply['major2'],
          "isadjust"=>$apply['isadjust'],
          "teacher"=>$apply['teacher'],
          "advice_note"=>$apply['advice_note'],
          "grade"=>$apply['grade'],
          "teacher_comment"=>$apply['teacher_comment'],
          "teacher_id"=>$apply['teacher_id'],
          "major_id"=>$apply['major_id'],
          "major2_id"=>$apply['major2_id'],
          "bktype_id"=>$apply['bktype_id'],
          "coursetype_name"=>$apply['coursetype_name'],
          "coursetype_id"=>$apply['coursetype_id'],
          "name"=>$user['name'],
          "pwd"=>$user['pwd'],
          "sex"=>$user['sex'],
          "phone"=>$user['phone'],
          "idcard"=>$user['idcard'],
          "user_create_time"=>strtotime($user['create_time']),
          "user_update_time"=>strtotime($user['update_time']),
          "nation"=>$user['nation'],
          "qqwx"=>$user['qqwx'],
          "parenttel"=>$user['parenttel'],
          "schooladdress"=>$user['schooladdress'],
          "schoolname"=>$user['schoolname'],
          "score"=>$user['score'],
          "address"=>$user['address'],
          "del_time"=>time(),
          "del_comment"=>$del_comment,
      );
      if (Dustbin::create($arr)) {
          User::destroy($apply['userid']);
          Apply::destroy($request->post('id'));
          Session::delete("user_infos");
          $this->success("已移入回收站", "Search/search");
      } else {
          $this->error("移入回收站失败", "Search/search");
      }
  }
  // 修改为待支付
  public function dzf(Request $request)
  {
    $data = $request->post();
    $data['status'] = 4;
    $data['type'] = 4;
    $res = Apply::update($data);
    if ($res) {
      $this->success("修改成功");
    } else {
      $this->error("修改失败");
    }
  }//------------------------------------------------------------------------------------------------------------------
  //修改报名记录为拒绝状态
  public function times(Request $request)
  {
    $user = $this->user_info();
    $data = $request->post();
    $data['status'] = 3;
    $data['type'] = 3;
    if (Apply::update($data)) {
      $this->success("修改成功");
    } else {
      $this->error("修改失败");
    }
  }
  //修改报名记录为通过状态
  public function check(Request $request)
  {
    $user = $this->user_info();
    $data = $request->post();
    $data['status'] = 2;
    $data['type'] = 2;
    if (Apply::update($data)) {
      $this->success("修改成功");
    } else {
      $this->error("修改失败");
    }
  }
  //修改学生为已录取
  public function classAddStudent(Request $request)
  {
    $data = $request->post();
    $data['type'] = 2;
    $data['status'] = 2;
    $data['update_time'] = time();
    if (Apply::update($data)) {
      //发送短信
      $apply = Apply::get($data['id']);
      $student = User::get($apply['userid']);
      $res = message($student['phone'],["name"=>$student['name'],"major"=>$apply['major']],3); //发送录取通知短信
      $msg_msg ="录取成功";
      if($res['stat'] == 100){
        $msg_msg .= ",短信发送：".$res['message'];
      }else{
        $msg_msg .= "，短信发送失败：".$res['message'];
      }
      $this->success($msg_msg);
    } else {
      $this->error("录取成功");
    }
  }
  //修改学生为报名审核中
  public function classAddStudent2(Request $request)
  {
    $data = $request->post();
    $data['type'] = 4;
    $data['status'] = 4;
    if (Apply::update($data)) {
      $apply = Apply::get($data['id']);
      $student = User::get($apply['userid']);
      $res = message($student['phone'],["name"=>$student['name'],"major"=>$apply['major']],2); //发送录取通知短信
      $msg_msg ="报名成功";
      if($res['stat'] == 100){
        $msg_msg .= ",短信发送：".$res['message'];
      }else{
        $msg_msg .= "，短信发送失败：".$res['message'];
      }
      $this->success($msg_msg);
    } else {
      $this->error("报名失败");
    }
  }
  //修改学生的专业
  public function update_major(Request $request)
  {
    $user = $this->user_info();
    $res = Apply::get($request->get("id"));
    $data = array(
      "pid" => $request->get("pid"),
      "apply" => $res,
      "user" => user::get($res['userid']),
      "examtype" => Examtype::select(),
      "teacher"=>Teacher::where('status',1)->select(), //老师没有被禁用的老师
      "major" => collection(Course::order('sort','asc')->select())->toArray(),
      "setting" => $this->getAllSetting(),
    );
    return view("update_major", $data);
  }
  //完成修改学生的专业
  public function save_update_major(Request $request)
  {
    $data = $request->post();
    $pid = $data["pid"];
    unset($data["pid"]);
    if (Apply::update($data)) {
      $this->success("修改成功","Search/search");
    } else {
      $this->error("修改失败");
    }
  }
  //生成图片
  public function create_advice(Request $request)
  {
    header('content-type:image/png');
    $user = $this->user_info();
    //查询用户信息和用户的报名信息
    $student = User::get($request->get("id"));
//    $student = User::get(213);
    $sex = $student['sex'] == 0 ? "女" : "男";
    $student_apply = Apply::where(["userid"=>$request->get('id')])->find();
//    $student_apply = Apply::where(["userid"=>	213])->find();
    $apply_node = $request->get("time");
    $width =2480;
    $height =3508;
    $img =imagecreatetruecolor($width,$height);
    $color = imagecolorallocate($img,255,255,255);
    $textcolor = imagecolorallocate($img,0,0,0);
    imagefill($img,0,0,$color);
//    imagestring($img,57,434,1225,$apply_node,$textcolor);
    imagettftext($img, 64, 0, 404, 1300, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", $apply_node);
    imagettftext($img, 60, 0, 233, 1448, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", $student['name']);
    imagettftext($img, 60, 0, 1604, 1594, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", $student_apply['major']);
    imagettftext($img, 65, 0, 458, 1737, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", "三");

    imagettftext($img, 64, 0, 2006, 2924, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", $apply_node);
    imagettftext($img, 60, 0, 379, 3095, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", $student['name']);
    imagettftext($img, 60, 0, 1478, 3095, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", $student_apply['major']);
    imagettftext($img, 60, 0, 379, 3221, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", $sex);
    imagettftext($img, 60, 0, 1478, 3221, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", "三");

    imagettftext($img, 54, 0, 1451, 3320, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", $this->big_number(date("Y")));
    imagettftext($img, 54, 0, 1913, 3320, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", $this->big_number(date("n")));
    imagettftext($img, 54, 0, 2123, 3320, $textcolor, ROOT_PATH."/public/static/admin/fonts/simsun.ttc", $this->big_number(date("d")));
    imagepng($img);
    imagedestroy($img);
    exit();
  }
  //将年月日转为汉字
  public function big_number($number){
    $str = "";
    $len = strlen($number);
    if($len == 4) {
      for ($i = 0; $i < $len; $i++) {
        switch (substr($number, $i, 1)) {
          case 1 :
            $str .= "一";
            break;
          case 2 :
            $str .= "二";
            break;
          case 3 :
            $str .= "三";
            break;
          case 4 :
            $str .= "四";
            break;
          case 5 :
            $str .= "五";
            break;
          case 6 :
            $str .= "六";
            break;
          case 7 :
            $str .= "七";
            break;
          case 8 :
            $str .= "八";
            break;
          case 9 :
            $str .= "九";
            break;
          case 0 :
            $str .= "〇";
            break;
        }
      }
    }else if($len == 2 ){
      switch (substr($number, 0, 1)) {
        case 1 :
          $str .= "十";
          break;
        case 2 :
          $str .= "二十";
          break;
        case 3 :
          $str .= "三十";
          break;
      }
      switch (substr($number, 1, 1)) {
        case 1 :
          $str .= "一";
          break;
        case 2 :
          $str .= "二";
          break;
        case 3 :
          $str .= "三";
          break;
        case 4 :
          $str .= "四";
          break;
        case 5 :
          $str .= "五";
          break;
        case 6 :
          $str .= "六";
          break;
        case 7 :
          $str .= "七";
          break;
        case 8 :
          $str .= "八";
          break;
        case 9 :
          $str .= "九";
          break;
        case 0 :
          $str .= "";
          break;
      }
    }else if($len == 1 ){
      switch ($number) {
        case 1 :
          $str .= "一";
          break;
        case 2 :
          $str .= "二";
          break;
        case 3 :
          $str .= "三";
          break;
        case 4 :
          $str .= "四";
          break;
        case 5 :
          $str .= "五";
          break;
        case 6 :
          $str .= "六";
          break;
        case 7 :
          $str .= "七";
          break;
        case 8 :
          $str .= "八";
          break;
        case 9 :
          $str .= "九";
          break;
      }
    }
    return $str;
  }
  //确认已经打印了通知书
  public function advice_node(Request $request){
    $data = $request->post();
    $pid = $data["pid"];
    unset($data["pid"]);
    //将通知书编号保存
    if (Apply::update($data)) {
      $this->success("通知书编号保存成功");
    } else {
      $this->error("通知书编号保存失败");
    }

  }
  //搜索学员
  public function search(){
     //多表联查报考类型-专业大类-专业
    $query_str = "select examtype.name as examtype_name,coursetype.name as coursetype_name,course.id as course_id,course.name as course_name from examtype,coursetype,course where examtype.id = course.examtype_id and coursetype.id = course.typeid;";
    $examtype_coursetype_course = \think\Db::query($query_str);
    //组织新的数组把查到的报考类型-专业大类-专业的名字连起来，只保留专业的id用于后续搜索
    $e_c_c = [];
    foreach($examtype_coursetype_course as $val){
        $e_c_c[] = ["ecc"=>"【{$val['examtype_name']}】-【{$val['coursetype_name']}】-【{$val['course_name']}】",'course_id'=>$val['course_id']];
    }
    //查询所有的报名状态
    $data = array(
      "setting" => $this->getAllSetting(),
      "status" => Applytype::order("sort asc")->select(),
      "course" => $e_c_c,
      "teacher"=>collection(Teacher::all())->toArray(),
      "nation"=>collection(Nation::all())->toArray(),
    );
    return view("search",$data);
  }

  //去搜索学员
  public function toSearch(Request $request){
    $user = $this->user_info();
    //接收搜索条件
    $data = $request->post();

    //组织条件
    $whereString  = "apply.userid = user.id and apply.type = applytype.id";
    //学生姓名
    if (!empty($data["name"] )){
      $whereString .= " and user.name like '%".$data["name"]."%'";
    }
    //学生年级
    if (!empty($data["grade"] )){
      $whereString .= " and user.grade like '%".$data["grade"]."%'";
    }
    //性别
    if ($data["sex"] != ""){
      $whereString .= " and user.sex = {$data["sex"]}";
    }
    //学生电话
    if (!empty($data["phone"])){
      $whereString .= " and user.phone like '%".$data["phone"]."%'";
    }
    //身份证
    if (!empty($data["idcards"])){
      $whereString .= " and user.idcard like '%".$data["idcards"]."%'";
    }
    //父母电话
    if (!empty($data["parenttel"])){
      $whereString .= " and user.parenttel like '%".$data["parenttel"]."%'";
    }
    //民族
    if (!empty($data["nation"])){
      $whereString .= " and user.nation like '%".$data["nation"]."%'";
    }

    //学校地址
    if (!empty($data["schooladdress"])){
      $whereString .= " and user.schooladdress like '%".$data["schooladdress"]."%'";

    }
    //学校名称
    if (!empty($data["schoolname"])){
      $whereString .= " and user.schoolname like '%".$data["schoolname"]."%'";
    }
    //通讯地址
    if (!empty($data["address"])){
      $whereString .= " and user.address like '%".$data["address"]."%'";
    }
    //第一专业
    if (!empty($data["major"])){
      $whereString .= " and apply.major_id = {$data["major"]}";
    }
    //状态
    if (!empty($data["status"])){
      $whereString .= " and apply.status = {$data["status"]}";
    }
    //支付类型
    if (!empty($data["paytype"])){
      $whereString .= " and apply.paytype like '%".$data["paytype"]."%'";

    }
    //支付账号
    if (!empty($data["payid"])){
      $whereString .= " and apply.payid like '%".$data["payid"]."%'";
    }
    //负责老师
    if (!empty($data["teacher"])){
      $whereString .= " and apply.teacher like '%".$data["teacher"]."%'";
    }
    //通知书编号
    if (!empty($data["advice_note"])){
      $whereString .= " and apply.advice_note like '%".$data["advice_note"]."%'";
    }
    //组织sql语句
    $sql = "select user.`id` as user_id,user.`name`,user.`grade`,user.`pwd` ,user.`sex`,user.`phone`,user.`idcard`,user.`create_time` as user_create_time,user.`update_time` as user_update_time,user.`nation` ,user.`qqwx`,user.`parenttel`,user.`schooladdress`,user.`schoolname`,user.`score`,user.`address`,apply.`id` as apply_id,apply.`userid`,apply.`major`,apply.`bktype`,apply.`create_time` as apply_create_time,apply.`update_time` as apply_update_time,apply.`reason`,apply.`comment`,apply.`status` as apply_status,apply.`paytype`,apply.`payid`,apply.`type`,apply.`pay_time`,apply.`major2`,apply.`isadjust`,apply.`teacher`,apply.`advice_note`,apply.`coursetype_name`,apply.`teacher_comment`,applytype.`id` as applytype_id,applytype.`type_name`,applytype.`status`,applytype.`create_time` as applytype_create_time,applytype.`update_time` as applytype_update_time from `user`,apply,applytype where ".$whereString;
    //查询数据
    $list = \think\Db::query($sql);
    //将数据组织为表格行
    $str = "";
    if(!empty($list)) {
      foreach($list as $v){
        $apply_create_time = !empty($v['apply_create_time']) ? date("Y-m-d H:i:s",$v['apply_create_time']) : "";
        $update_time = !empty($v['apply_update_time']) ? date("Y-m-d H:i:s",$v['apply_update_time']) : "未修改";
        $pay_time = !empty($v['pay_time']) ? date("Y-m-d H:i:s",$v['pay_time']) : "无";
        $sex = $v['sex']?"男":"女";
        $status_msg = "";
        $cz = "";
        switch($v['apply_status']) {
          case 1 :
            $status_msg = "<span style=\"color:#f8ac59\"><i class=\"fa fa-thumb-tack\"></i> 缴费核对中</span>";
            $cz = "<a class=\"rotate\" title='修改未支付' data-username=\"{$v['name']}\" data-id=\"{$v['apply_id']}\"><i class=\"fa fa-rotate-left\" style=\"color:#19a9d5\" data-type=\"{$v['type']}\"></i></a>
                                                    <a class=\"check\" title='确认录取'  data-username=\"{$v['name']}\" data-courses=\"\" data-times=\"{$apply_create_time}\" data-id=\"{$v['apply_id']}\" data-type=\"{$v['type']}\" data-idcard=\"{$v['idcard']}\" data-bktype=\"{$v['bktype']}\" data-major=\"{$v['major']}\" data-major2=\"{$v['major2']}\" data-isadjust=\"{$v['isadjust']}\" data-paytype=\"{$v['paytype']}\" data-teacher=\"{$v['teacher']}\" data-paytime=\"{$pay_time}\" data-payid=\"{$v['payid']}\"><i class=\"fa fa-check\" style=\"color:#79c667\"></i></a>";
            break;
          case 2 :
            $cz = "<a href=\"/public/index.php/admin/search/update_major?id={$v['apply_id']}&pid={$v['applytype_id']}\" title='修改专业'><i class=\"fa fa-pencil\" style=\"color:#19a9d5\" data-type=\"{$v['type']}\"></i></a>
                                             
                                                    <a class=\"print\" data-name=\"{$v['name']}\" data-id=\"{$v['user_id']}\" data-applyid=\"{$v['apply_id']}\" data-pid=\"{$v['applytype_id']}\" title='打印报到证'><i class=\"fa fa-print\" style=\"color:#000000\" data-type=\"{$v['type']}\"></i></a>";
            $status_msg = "<span style=\"color:green\"><i class=\"fa fa-check\"></i> 已录取</span>";
            break;
          case 3 :

            $status_msg = "<span style=\"color:#d9534f;\"><i class=\"fa fa-times\"></i> 拒绝</span>";
            break;
          case 4 :
            $cz = "<a title='修改专业' href=\"/public/index.php/admin/search/update_major?id={$v['apply_id']}&pid={$v['applytype_id']}\"><i class=\"fa fa-pencil\" style=\"color:#19a9d5\" data-type=\"{$v['type']}\"></i></a> <a title='打印报到证' class=\"print\" data-name=\"{$v['name']}\" data-id=\"{$v['user_id']}\" data-applyid=\"{$v['apply_id']}\" data-pid=\"{$v['applytype_id']}\"><i class=\"fa fa-print\" style=\"color:#000000\" data-type=\"{$v['type']}\"></i></a>";
            $status_msg = "<span style=\"color:#19a9d5;\"><i class=\"fa fa-times\"></i> 待支付</span>";
            break;
          case 5 :
            $status_msg = "<span style=\"color:#f8ac59;\"><i class=\"fa fa-thumb-tack\"></i> 报名核对中</span>";
            $cz = " <a title='确认支付' class=\"pass\"  data-username=\"{$v['name']}\" data-courses=\"\" data-times=\"{$apply_create_time}\" data-id=\"{$v['apply_id']}\" data-teacher=\"{$v['teacher']}\" data-type=\"{$v['type']}\" data-idcard=\"{$v['idcard']}\" data-bktype=\"{$v['bktype']}\" data-major=\"{$v['major']}\" data-major2=\"{$v['major2']}\" data-isadjust=\"{$v['isadjust']}\" ><i class=\"fa fa-check-square-o\" style=\"color:#79c667\"></i></a>
                                                    <a title='拒绝报名' class=\"times\" data-id=\"{$v['apply_id']}\" data-type=\"{$v['type']}\" ><i class=\"fa fa-times\" style=\"color:#d9534f\"></i></a>";
            break;
        }
        $cz .=  " <a class=\"del\" title='移入回收站' data-id=\"{$v['apply_id']}\" data-type=\"{$v['type']}\"><i class=\"fa fa-trash\" style=\"color:#cacfd3\"></i></a>";
        $reason = empty($v['reason']) ? "无" : $v['reason'];

        $str .= "
          <tr>
              <td>{$v['user_id']}</td>`
              <td>{$v['grade']}</td>
              <td>{$v['name']}</td>
              <td>{$v['phone']}</td>
              <td>{$v['parenttel']}</td>
              <td>{$v['bktype']}</td>
              <td>{$v['coursetype_name']}</td>
              <td>{$v['major']}</td>
              <td>{$v['major2']}</td>
              <td>{$v['isadjust']}</td>
              <td>{$v['teacher']}</td>
              <td>".date('Y-m-d h:i:s',$v['apply_create_time'])."</td>
              <td>".$status_msg."</td>
              <td>{$v['advice_note']}</td>
              <td class=\"tools\">
                  ".$cz."
              </td>
               <!--隐藏起来的列表信息-->
              <td>{$sex}</td>
              <td>{$v['nation']}</td>
              <td>{$v['qqwx']}</td>
              <td>{$v['schooladdress']}</td>
              <td>{$v['schoolname']}</td>
              <td>{$v['score']}</td>
              <td>{$v['idcard']}</td>
              <td>{$v['address']}</td>
              <td>".$update_time."</td>
              <td>{$v['paytype']}</td>
              <td>{$v['payid']}</td>
              <td>".$pay_time."</td>
              <td>{$v['comment']}</td>
              <td>{$v['teacher_comment']}</td>
              <td>{$reason}</td>
          </tr>";
      }
      $this->success($str);
    }else{
      $this->success("<tr><td colspan=''>未查到数据</td></tr>");
    }

  }
}